package com.ecar.api.service.common.impl;

import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ecar.api.service.common.PriceCalculateService;
import com.ecar.api.support.dto.Constants;
import com.ecar.api.support.dto.ForecastPriceDetailDto;
import com.ecar.api.support.util.UuidUtils;
import com.ecar.common.dto.DataBean;
import com.ecar.core.common.dao.PriceRuleMapper;
import com.ecar.core.common.entity.PriceRule;
import com.ecar.core.driver.dao.CarMapper;
import com.ecar.core.driver.entity.Car;
import com.ecar.core.order.dao.OrderMapper;
import com.ecar.core.order.dao.OrderPriceDetailMapper;
import com.ecar.core.order.dao.OrderPriceRuleMapper;
import com.ecar.core.order.entity.Order;
import com.ecar.core.order.entity.OrderPriceDetail;
import com.ecar.core.order.entity.OrderPriceRule;
import com.esotericsoftware.minlog.Log;

import net.sf.json.JSONObject;

@Service
@Transactional
public class PriceCalculateServiceImpl implements PriceCalculateService {

	@Autowired
	CarMapper carMapper;

	@Autowired
	OrderPriceRuleMapper orderPriceRuleMapper;

	@Autowired
	OrderMapper orderMapper;

	@Autowired
	OrderPriceDetailMapper orderPriceDetailMapper;

	/*
	 * @Override public ForecastPriceDetailDto jsjForecastPriceDetail(int
	 * carLevel, double distance) { ForecastPriceDetailDto fDetailDto = new
	 * ForecastPriceDetailDto(); //查询路程费率 OrderPriceRule orderPriceRule =
	 * orderPriceRuleService.selectByPrimaryKey(carLevel); //起步价
	 * fDetailDto.setStartPrice(orderPriceRule.getStartPrice()); //里程费
	 * fDetailDto.setDistancePrice(orderPriceRule.getRoadPrice() *distance);
	 * //远途费 if (distance > 20) {
	 * fDetailDto.setLongPrice((distance-20)*orderPriceRule.getLongPrice());
	 * }else { fDetailDto.setLongPrice(0.0); } //低速费
	 * fDetailDto.setLowPrice(0.0); return fDetailDto; }
	 */
	/**
	 * 插入价格详情，结束行程调用
	 * 
	 * @param orderNum
	 * @param emptyDriverDistance
	 * @param roadDistance
	 * @param orderStatus
	 *            0:订单取消,1:等待接单2:司机已接单3:到达上车点4:开始行程5:结束行程
	 * @return
	 */
	@Override
	public DataBean getReceiveOrSendOrderPriceDetail(String orderNum, double emptyDriverDistance, double roadDistance,
			int driverTime, double addCharge) {

		// 订单信息
		Order order = orderMapper.selectByOrderNum(orderNum);
		/**
		 * fire线下单
		 */
		if (order.getOrderType() == 6) {
			OrderPriceDetail orderPriceDetail = new OrderPriceDetail();
			orderPriceDetail.setId(UuidUtils.getUUID());
			orderPriceDetail.setDriverId(order.getDriverId());
			orderPriceDetail.setPassengerId(order.getPassengerId() + "");
			orderPriceDetail.setOrderNum(orderNum);
			orderPriceDetail.setTotalPrice(order.getUseSeats() * 45 + 0.00);

			int pk = orderPriceDetailMapper.insertSelective(orderPriceDetail);
			if (pk < 1) {
				return new DataBean(400, new JSONObject(), "订单结束状态设置失败");
			}
			orderMapper.updateByOrderNum(orderNum, new Date(), Constants.END_ROAD, orderPriceDetail.getTotalPrice(),
					Order.ST.CREATED.val());
			return new DataBean(200, new JSONObject(), "订单详情插入成功");
		}

		if (order == null) {
			return new DataBean(400, new JSONObject(), "无此订单信息");
		}
		String driverId = order.getDriverId();

		// 查询司机车辆档案信息
		Car car = carMapper.selectByDriverId(driverId);
		if (car == null) {
			return new DataBean(400, new JSONObject(), "无此司机车辆类型信息");
		}
		// 获取车辆收费规则信息
		OrderPriceRule orderPriceRule = orderPriceRuleMapper.selectByCode(car.getSeatType(), order.getOrderType());
		if (orderPriceRule == null) {
			return new DataBean(400, new JSONObject(), "收费规则信息查询失败");
		}
		// 基础价
		double basePrice = orderPriceRule.getMinPrice();
		OrderPriceDetail orderPriceDetail = new OrderPriceDetail();
		if (order.getOrderType() == 1 || order.getOrderType() == 2) {// 接送机

			// 超基础里程金额
			double overMileagePrice = 0.0;
			if (Math.floor(roadDistance) < roadDistance && roadDistance < Math.ceil(roadDistance)) {
				roadDistance = Math.ceil(roadDistance);
			}
			if (roadDistance > 30.0) {
				overMileagePrice = orderPriceRule.getPassRate() * (roadDistance - 30.0);
			}

			// 超时金额
			double overTimePrice = 0.0;
			Calendar endDate = Calendar.getInstance();
			Calendar startDate = Calendar.getInstance();
			startDate.setTime(order.getStartTime());// 开始行程时间
			endDate.setTime(new Date());
			long timeEnd = endDate.getTimeInMillis();
			long timeStart = startDate.getTimeInMillis();
			int minuteSeparated = (int) ((timeEnd - timeStart) / (1000 * 60));
			Log.info("行程用时：" + (timeEnd - timeStart));
			if (minuteSeparated < 0) {
				return new DataBean(400, new JSONObject(), "开始时间不能大于结束时间");
			}
			Log.info("========行程用时" + minuteSeparated + "分========");
			if ((minuteSeparated - 30.0) > 0) {
				overTimePrice = (minuteSeparated - 30.0) * 0.7;
			}

			// 空驶金额
			double emptyDriverPrice = 0.0;
			if (emptyDriverDistance > 30.0) {
				emptyDriverPrice = (emptyDriverDistance - 30) * 1.0;
			}

			// 夜间服务费
			double totalNightPrice = 0.0;
			Calendar c1 = Calendar.getInstance();
			startDate.setTime(order.getStartTime());// 开始行程时间
			int houre = c1.get(Calendar.HOUR_OF_DAY);
			if (houre >= 23 || houre < 6) {
				totalNightPrice = 1.0;
			}

			// 总费用
			double totalPrice = basePrice + overMileagePrice + overTimePrice + emptyDriverPrice + totalNightPrice
					+ addCharge;
			// 更新订单表数据
			int num = orderMapper.updateByOrderNum(orderNum, new Date(), Constants.END_ROAD, totalPrice,
					Order.ST.CREATED.val());

			// 插入订单费用详情表
			orderPriceDetail.setBasePrice(basePrice);
			orderPriceDetail.setDriverId(driverId);
			orderPriceDetail.setDriverTime(minuteSeparated);
			orderPriceDetail.setEmptyDriverPrice(emptyDriverPrice);
			orderPriceDetail.setEmptyRoadDistance(emptyDriverDistance);
			orderPriceDetail.setId(UuidUtils.getUUID());
			orderPriceDetail.setLightDriverPrice(totalNightPrice);
			orderPriceDetail.setOrderNum(orderNum);
			orderPriceDetail.setOverMileagePrice(overMileagePrice);
			orderPriceDetail.setOverTimePrice(overTimePrice);
			orderPriceDetail.setPassengerId(order.getPassengerId().toString());
			orderPriceDetail.setRoadDistance(roadDistance);
			orderPriceDetail.setTotalPrice(totalPrice);
			orderPriceDetail.setAddCharge(addCharge);
			OrderPriceDetail selectOrderPriceDetail = orderPriceDetailMapper.selectByOrderNum(orderNum);
			if (selectOrderPriceDetail == null) {
				int nu = orderPriceDetailMapper.insertSelective(orderPriceDetail);
				if (nu <= 0) {
					return new DataBean(400, new JSONObject(), "订单结束状态设置失败");
				}
			}
			return new DataBean(200, new JSONObject(), "订单详情插入成功");
		} else if (order.getOrderType() == 3 || order.getOrderType() == 4) {// 快车实时和预约
			// 里程价
			double overMileagePrice = 0.0;
			roadDistance = Math.ceil(roadDistance);

			if (roadDistance > orderPriceRule.getMenuRate()) {
				overMileagePrice = orderPriceRule.getPassRate() * (roadDistance - orderPriceRule.getMenuRate());
			}

			// 时长价格
			Calendar endDate = Calendar.getInstance();
			Calendar startDate = Calendar.getInstance();
			startDate.setTime(order.getStartTime());// 开始行程时间
			endDate.setTime(new Date());
			long timeEnd = endDate.getTimeInMillis();
			long timeStart = startDate.getTimeInMillis();
			int minuteSeparated = (int) ((timeEnd - timeStart) / (1000 * 60));
			Log.info("行程用时：" + (timeEnd - timeStart));
			if (minuteSeparated < 0) {
				return new DataBean(400, new JSONObject(), "开始时间不能大于结束时间");
			}
			Double timePrice = 0.0;
			Double menuTime = orderPriceRule.getMenuTime();
			Double passTimePrice = orderPriceRule.getPassTime();
			if (minuteSeparated > menuTime) {
				timePrice = (minuteSeparated - menuTime) * passTimePrice;
			}

			// 远途费
			double longDistanceTotalPrice = 0.0;
			Double longDistanceRate = orderPriceRule.getLongDistanceRate();
			Double longDistancePrice = orderPriceRule.getLongDistancePrice();
			if (roadDistance > longDistanceRate) {
				longDistanceTotalPrice = longDistancePrice * (roadDistance - longDistanceRate);
			}

			// 夜间服务费
			double totalNightPrice = 0.0;
			Calendar c1 = Calendar.getInstance();
			int houre = c1.get(Calendar.HOUR_OF_DAY);
			if (houre >= 23 || houre < 6) {
				totalNightPrice = orderPriceRule.getNightPrice() * roadDistance;
			}
			// 总费用
			double totalPrice = basePrice + overMileagePrice + totalNightPrice + addCharge + timePrice
					+ longDistanceTotalPrice;
			// 更新订单表数据
			int num = orderMapper.updateByOrderNum(orderNum, new Date(), Constants.END_ROAD, totalPrice,
					Order.ST.CREATED.val());
			// 插入订单费用详情表
			orderPriceDetail.setId(UuidUtils.getUUID());
			orderPriceDetail.setDriverId(driverId);
			orderPriceDetail.setOrderNum(orderNum);
			orderPriceDetail.setPassengerId(order.getPassengerId().toString());
			orderPriceDetail.setBasePrice(basePrice);
			orderPriceDetail.setOverMileagePrice(overMileagePrice);
			orderPriceDetail.setLightDriverPrice(totalNightPrice);
			orderPriceDetail.setTotalPrice(totalPrice);
			orderPriceDetail.setRoadDistance(roadDistance);
			orderPriceDetail.setAddCharge(addCharge);
			orderPriceDetail.setTimePrice(timePrice);
			orderPriceDetail.setLongDistancePrice(longDistanceTotalPrice);
			OrderPriceDetail selectOrderPriceDetail = orderPriceDetailMapper.selectByOrderNum(orderNum);
			if (selectOrderPriceDetail == null) {
				int nu = orderPriceDetailMapper.insertSelective(orderPriceDetail);
				if (nu <= 0) {
					return new DataBean(400, new JSONObject(), "订单详情插入失败");
				}
			}
		}
		// 将费用更新到订单详细表
		return new DataBean(200, new JSONObject(), "订单详情插入成功");
	}

	@Override
	public OrderPriceDetail selectByOrderNum(String orderNum) {
		return orderPriceDetailMapper.selectByOrderNum(orderNum);
	}

	@Override
	public OrderPriceRule selectPriceRule(int carLevel, int serviceType) {
		return orderPriceRuleMapper.selectByCode(carLevel, serviceType);
	}

}
